import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import numpy as np
import cv2

from protocol.decorators import edp_service, instant, instant_req
# PoseFlat:=(Float,Float,Float)
# DistributeStimulus:=(Position, Frequency)
@edp_service
class DataProcessingService:
    name = "data-processing"
    desc = ""
    tasks = [
        "generate_dataset_lrstim:(List<(PoseFlat, Confidence)>, List<(Int, Int)>, List<(Int, Int)>, Frequency, ?Str) -> Str",
        "point_selector: (Str,Int)->PointI"
    ]
    @instant
    def generate_dataset_lrstim(self, inputs):
        pose = inputs[0]
        lstim = inputs[1]
        rstim = inputs[2]
        freq = inputs[3]
        fout = inputs[4]
        fps = 15
        
        nf = len(pose)
        fdist = np.zeros((nf, 2))
        for s, e in lstim:
            for i in range(s, e):
                fdist[i][0] = freq
        for s, e in rstim:
            for i in range(s, e):
                fdist[i][1] = freq
        
        ng = nf - 5 * fps
        dt = np.zeros((ng, 6, 5))
        for i in range(ng):
            x0, y0 = pose[i][0][:2]
            for j in range(6):
                k = i + j * 15
                dt[i][j] = np.hstack((pose[k][0][0] - x0, pose[k][0][1] - y0, pose[k][0][2], fdist[k]))
        if fout:
            np.savez(fout + "/ds.npz", dt)
        else:
            np.savez("ds.npz", dt)
        return fout
    def point_selector(self, inputs):
        filepath = inputs[0]
        frame = inputs[1]
        cap = cv2.VideoCapture(filepath)
        cap.set(1,frame)
        ret, img = cap.read()
        if not ret:
            print(f'读取失败: {frame}')
            return [-1, -1]
        def mouse_callback(event, x, y, flags, param):
            if event == cv2.EVENT_LBUTTONDOWN:
                param[0] = [x, y]
                cv2.destroyAllWindows()
        
        point = [None]
        cv2.namedWindow('image')
        cv2.setMouseCallback('image', mouse_callback, point)
        while True:
            cv2.imshow('image', img)
            if cv2.waitKey(1) & 0xFF == 27 or point[0] is not None:  # ESC键退出
                break
        cv2.destroyAllWindows()
        cap.release()
        
        if point[0] is None:
            return [-1, -1]
        p = list(point[0])
        print(p)
        return p

if __name__ == '__main__':
    DataProcessingService().app.run(port=5050, debug=True)
    # fp = r"C:\Users\songy\Desktop\fyp-songy-2025-05-17\videos\fyp_20250326172041.mp4"
    # o = DataProcessingService()
    # o.point_selector((fp, 15))

    # import json
    # pose = json.load(open(r"C:\Users\songy\Desktop\data-0530\pose.json"))
    # lstim = json.load(open(r"C:\Users\songy\Desktop\data-0530\lstim-seg.json"))
    # rstim = json.load(open(r"C:\Users\songy\Desktop\data-0530\rstim-seg.json"))
    # freq = 30
    # res = DataProcessingService().generate_dataset_lrstim((pose, lstim, rstim, freq, None))
    # print(res[0])
    # np.savez(r"C:\Users\songy\Desktop\data-0530\ds.npz", res)

    # for s, _, _ in lstim:
    #     l = fps * 0.6
    #     b = s - l
    #     for i in range(fps * 0.6):
    #         if b + i < 0:
    #             continue
    #         fdist[b + i][0] += i / l * freq
    #     fdist[s] = freq
    #     l = fps * 2
    #     b = s + l
    #     for j in range(fps * 2):
    #         if b - j >= nf:
    #             continue
    #         fdist[b - j][0] += j / l * freq